﻿using System;
using System.Configuration;
using System.Net.Mail;
using System.Web.Configuration;
using Altairis.MailToolkit.Configuration;

namespace Altairis.MailToolkit.Transport {

    /// <summary>
    /// Helper class for using transport providers
    /// </summary>
    public static class TransportManager {

        static TransportManager() {
            // Get configuration info
            var config = ConfigurationManager.GetSection("altairis.mailToolkit") as MailToolkitConfigurationSection;

            // Instantiate providers
            Providers = new TransportProviderCollection();
            if (config != null && config.Transport.Providers != null && config.Transport.Providers.Count != 0) {
                ProvidersHelper.InstantiateProviders(config.Transport.Providers, Providers, typeof(TransportProvider));

                // Return default provider
                DefaultProvider = Providers[config.Transport.DefaultProvider] as TransportProvider;
                if (DefaultProvider == null) throw new ConfigurationErrorsException("No default mail transport provider specified.");
            }
            Providers.SetReadOnly();
        }

        /// <summary>
        /// Gets the configured default provider.
        /// </summary>
        /// <value>
        /// The configured default provider or <c>null</c>, when no default provider is configured.
        /// </value>
        public static TransportProvider DefaultProvider { get; private set; }

        /// <summary>
        /// Gets the transport providers.
        /// </summary>
        /// <value>
        /// The collection of transport providers.
        /// </value>
        public static TransportProviderCollection Providers { get; private set; }

        /// <summary>
        /// Sends the message using default provider or default .NET configured SmtpClient.
        /// </summary>
        /// <param name="msg">The message to be send.</param>
        /// <exception cref="System.ArgumentNullException">The <c>msg</c> parameter is null.</exception>
        public static void SendMessage(MailMessage msg) {
            if (msg == null) throw new ArgumentNullException("msg");

            if (DefaultProvider == null) {
                // No default provider specified - send directly using default .NET configuration
                using (var mx = new SmtpClient()) {
                    mx.Send(msg);
                }
            }
            else {
                // Send using default provider
                DefaultProvider.SendMessage(msg);
            }
        }
    }
}